const { query } = require("../../db/db");
const md5 = require("md5-node");
const multer = require("multer");

//管理员API
let data;

//上传文件
var datatime = "././public/images/avatar/";
//将图片放到服务器
var storage = multer.diskStorage({
  // 如果你提供的 destination 是一个函数，你需要负责创建文件夹
  destination: datatime,
  // //给上传文件重命名，获取添加后缀名
  filename: function (req, file, cb) {
    cb(null, new Date().getTime() + ".jpg");
  },
});
var upload = multer({
  storage: storage,
});
(exports.upLoadImg = upload.any()),
  (req, res) => {
    res.json({ success_code: 200, data: req.files });
    console.log(req.files);
  };

//登录
exports.login = async (req, res) => {
  let name = req.body.name;
  let password = md5(req.body.password);

  let sql = "SELECT * FROM admin WHERE name = ? LIMIT 1 ;";

  const result = await query(sql, [name, password]);

  try {
    if (result[0]) {
      if (result[0].password === password) {
        //保存用户id
        req.session.adminId = result[0].admin_id;
        res.cookie("admin_id", result[0].admin_id);
        data = { success_code: 200 };
      } else {
        data = { error_code: 1, message: "密码错误" };
      }
    } else {
      data = { error: 1, message: "用户不存在" };
    }
  } catch (error) {
    data = { error_code: 1, message: "查询用户失败" };
  }
  res.json(data);
};

//获取管理员用户信息
exports.getAdminInfo = async (req, res) => {
  let adminId = req.query.adminId;

  let sql = "SELECT * FROM admin WHERE admin_id = ? LIMIT 1 ;";

  const result = await query(sql, [adminId]);

  try {
    if (result[0]) {
      data = { success_code: 200, data: result[0] };
    } else {
      data = { error: 1, message: "用户不存在" };
    }
  } catch (error) {
    data = { error_code: 1, message: "查询用户失败" };
  }
  res.json(data);
};

//分页模糊查询显示用户的信息
exports.getCurrentPageUser = async (req, res) => {
  let { currentPage, pageSize, input } = req.query;
  let start = Number((currentPage - 1) * pageSize);
  pageSize = Number(pageSize);
  try {
    let sql = "SELECT * FROM user WHERE user_name LIKE ? ORDER BY user_id;";
    let total;
    const result = await query(sql, ["%" + input + "%"]);
    if (result[0]) {
      total = result.length;
    } else {
      console.log(error);
    }
    sql =
      "SELECT * FROM user WHERE user_name LIKE ? ORDER BY user_id LIMIT ?,?;";
    const result2 = await query(sql, ["%" + input + "%", start, pageSize]);
    data = { success_code: 200, data: result2, total: total };
  } catch (error) {
    data = { error_code: 1, message: "查询用户失败" };
  }
  res.json(data);
};

//更新用户信息
exports.updateUserInfo = async (req, res) => {
  try {
    let { userId, userName, avatar, password, sex, sign, birthday } = req.body;
    if (userId) {
      let sql = "SELECT * from user WHERE user_id = ? LIMIT 1;";
      const result = await query(sql, [userId]);
      if (result[0]) {
        //更新数据库
        let sql =
          "UPDATE user SET user_name = ?,avatar = ?,password = ?,sex = ? ,birthday = ?,sign = ?WHERE user_id = ?;";
        const result = await query(sql, [
          userName,
          avatar,
          password,
          sex,
          birthday,
          sign,
          userId,
        ]);
        data = { success_code: 200 };
      } else {
        data = { error_code: 1, message: "更新用户信息失败" };
      }
    }
  } catch (error) {
    data = { error_code: 1, message: "该用户不存在" };
  }
  res.json(data);
};

//删除用户信息
exports.deleteUserInfo = async (req, res) => {
  try {
    let { userId } = req.body;
    if (userId) {
      let sql = "SELECT * from user WHERE user_id = ? LIMIT 1;";
      const result = await query(sql, [userId]);
      if (result[0]) {
        //更新数据库
        let sql = "DELETE FROM user WHERE user_id =?";
        const result = await query(sql, [userId]);
        data = { success_code: 200, message: "删除成功" };
      } else {
        data = { error_code: 1, message: "未找到该用户" };
      }
    }
  } catch (error) {
    data = { error_code: 1, message: "删除失败" };
  }
  res.json(data);
};

//注册添加用户
exports.addUserInfo = async (req, res) => {
  try {
    let { userName, avatar, password, sex, sign, birthday, phone } = req.body;
    if (!avatar) {
      avatar = "/images/avatar/monkey.png";
    }
    let pwd = md5(password);
    let sql = "SELECT * FROM user WHERE user_name = ? LIMIT 1;";
    const result = await query(sql, [userName]);
    if (result.length !== 0) {
      data = { error_code: 1, message: "用户名已存在" };
    } else {
      sql = "SELECT * FROM user WHERE phone = ? LIMIT 1";
      const result = await query(sql, [phone]);
      if (result.length !== 0) {
        data = { error_code: 1, message: "手机号码已注册" };
      } else {
        sql =
          "INSERT INTO user(user_name,avatar,phone,password,sex,sign,birthday) VALUES(?,?,?,?,?,?,?);";
        const result = await query(sql, [
          userName,
          avatar,
          phone,
          pwd,
          sex,
          sign,
          birthday,
        ]);
        data = { success_code: 200, message: "注册成功" };
      }
    }
  } catch (error) {
    data = { error_code: 1, message: "失败了" };
  }
  res.json(data);
};

// //获取当前页影院
exports.getCurrentPageCinema = async (req, res) => {
  try {
    let { currentPage, pageSize, input } = req.query;
    let start = Number((currentPage - 1) * pageSize);
    pageSize = Number(pageSize);

    let sql =
      "SELECT * FROM cinema WHERE cinema_name LIKE ? ORDER BY cinema_id ;";
    let total;
    const result = await query(sql, ["%" + input + "%"]);
    if (result[0]) {
      total = result.length;
      sql =
        "SELECT * FROM cinema WHERE cinema_name LIKE ? ORDER BY cinema_id LIMIT ?,?;";
      const result2 = await query(sql, ["%" + input + "%", start, pageSize]);
      data = { success_code: 200, data: result2, total: total };
    } else {
      data = { error_code: 1, message: "未找到" };
    }
    res.json(data);
  } catch (error) {}
};

//更新影院信息
exports.updateCinemaInfo = async (req, res) => {
  try {
    let { cinemaId, cinemaName, cinemaPhone, address } = req.body;

    let sql = "SELECT * from cinema WHERE cinema_id = ? LIMIT 1;";
    const result = await query(sql, [cinemaId]);
    if (result.length !== 0) {
      let sql =
        "SELECT * FROM cinema WHERE cinema_name = ? AND cinema_id <> ? LIMIT 1 ;";
      const result = await query(sql, [cinemaName, cinemaId]);
      if (result.length !== 0) {
        data = { error_code: 1, message: "影院名已存在" };
      } else {
        sql =
          "UPDATE cinema SET cinema_name = ?,cinema_phone = ?,specified_address = ? WHERE cinema_id = ?;";
        const result = await query(sql, [
          cinemaName,
          cinemaPhone,
          address,
          cinemaId,
        ]);
        data = { success_code: 200, message: "更新影院信息成功" };
      }
    }
  } catch (error) {
    data = { error_code: 1, message: "更新影院信息失败" };
  }
  res.json(data);
};

//删除影院信息
exports.deleteCinemaInfo = async (req, res) => {
  try {
    let { cinemaId } = req.body;
    let sql = "DELETE FROM cinema WHERE cinema_id =?";
    const result = await query(sql, [cinemaId]);
    data = { success_code: 200, message: "删除影院成功" };
  } catch (error) {
    data = { error_code: 1, message: "删除影院失败" };
  }
  res.json(data);
};

//添加影院信息
exports.addCinemaInfo = async (req, res) => {
  try {
    let { cinemaName, cinemaPhone, address } = req.body;
    let sql = "SELECT * FROM cinema WHERE cinema_name = ? LIMIT 1 ;";
    const result = await query(sql, [cinemaName]);
    if (result.length !== 0) {
      data = { error_code: 1, message: "影院名已存在" };
    } else {
      sql =
        "INSERT INTO cinema(cinema_name,cinema_phone,specified_address) VALUES(?,?,?);";
      const result = await query(sql, [cinemaName, cinemaPhone, address]);
      data = { success_code: 200, message: "新增影院信息成功" };
    }
  } catch (error) {
    data = { error_code: 1, message: "新增影院信息失败" };
  }
  res.json(data);
};

//获取当前页评论
exports.getCurrentPageComment = async (req, res) => {
  try {
    let { currentPage, pageSize, input } = req.query;
    let start = Number((currentPage - 1) * pageSize);
    pageSize = Number(pageSize);

    let sql =
      "SELECT * FROM comment INNER JOIN movie ON comment.movie_id = movie.movie_id INNER JOIN user ON user.user_id=comment.user_id WHERE movie.name LIKE ? ORDER BY comment_id;";
    let total;
    const result = await query(sql, ["%" + input + "%"]);
    if (result.length == 0) {
      data = { error_code: 1, message: "error" };
    } else {
      total = result.length;
    }
    let sql2 =
      "SELECT * FROM comment INNER JOIN movie ON comment.movie_id = movie.movie_id INNER JOIN user ON user.user_id=comment.user_id WHERE movie.name LIKE ? ORDER BY comment_id LIMIT ?,?;";

    const result2 = await query(sql2, ["%" + input + "%", start, pageSize]);
    if (result2.length == 0) {
      data = { error_code: 1, message: "error" };
    } else {
      data = { success_code: 200, data: result, total: total };
    }
  } catch (error) {
    data = { error_code: 1, message: "未找到评论内容" };
  }
  res.json(data);
};

//通过当前评论
exports.passCurrentComment = async (req, res) => {
  try {
    let { commentId, movieId } = req.body;
    if (commentId) {
      let sql = "UPDATE comment SET is_pass = 1 WHERE comment_id = ?;";

      const result = await query(sql, [commentId]);
      if (result.length == 0) {
        data = { error_code: 1, message: "error" };
      } else {
        sql2 =
          "SELECT user_score FROM comment WHERE movie_id = ? AND is_pass = ?;";
        const result2 = await query(sql2, [movieId, 1]);
        if (result2.length === 0) {
          data = { error_code: 1, message: "没有找到评论" };
        } else {
          let avgScore = 0;
          if (result2.length) {
            result2.forEach((val) => {
              avgScore += Number(val.user_score);
            });
            avgScore = (avgScore / Number(result2.length)).toFixed(1);
          }
          sql3 = "UPDATE movie SET score = ? WHERE movie_id = ?;";
          const result3 = await query(sql2, [avgScore, movieId]);
          if (result3) {
            data = { success_code: 200, message: "通过评论成功" };
          }
        }
      }
    }
  } catch (error) {
    data = { error_code: 1, message: "未找到评论内容" };
  }
  res.json(data);
};

//删除当前评论
exports.deleteCurrentComment = async (req, res) => {
  try {
    let { commentId, movieId } = req.body;
    if (commentId.length == 0) {
      let sql = "DELETE FROM comment WHERE comment_id = ?;";

      const result = await query(sql, [commentId]);
      if (result.length == 0) {
        data = { error_code: 1, message: "error" };
      } else {
        sql2 =
          "SELECT user_score FROM comment WHERE movie_id = ? AND is_pass = ?;";
        const result2 = await query(sql2, [movieId, 1]);
        if (result2.length !== 0) {
          data = { error_code: 1, message: "没有找到评论" };
        } else {
          let avgScore = 0;
          if (result2.length) {
            result2.forEach((val) => {
              avgScore += Number(val.user_score);
            });
            avgScore = (avgScore / Number(result2.length)).toFixed(1);
          }
          sql3 = "UPDATE movie SET score = ? WHERE movie_id = ?;";
          const result3 = await query(sql3, [avgScore, movieId]);
          if (result3) {
            data = { success_code: 200, message: "删除评论成功" };
          }
        }
      }
    } else {
      data = { error_code: 1, message: "未找到评论内容" };
    }
  } catch (error) {
    data = { error_code: 1, message: "未找到评论内容" };
  }
  res.json(data);
};

//订单相关接口

//获取当前页订单
exports.getCurrentPageOrder = async (req, res) => {
  try {
    let { currentPage, pageSize, input } = req.query;
    let start = Number((currentPage - 1) * pageSize);
    pageSize = Number(pageSize);

    let sql =
      "SELECT * FROM orders INNER JOIN schedule ON orders.schedule_id = schedule.schedule_id INNER JOIN movie ON movie.movie_id = schedule.movie_id INNER JOIN cinema ON cinema.cinema_id = schedule.cinema_id INNER JOIN user ON orders.user_id = user.user_id WHERE movie.name LIKE ? ORDER BY order_id;";
    let total;
    const result = await query(sql, ["%" + input + "%"]);
    if (result.length == 0) {
      data = { error_code: 1, message: "未找到订单内容" };
    } else {
      total = result.length;
    }
    let sql2 =
      "SELECT * FROM orders INNER JOIN schedule ON orders.schedule_id = schedule.schedule_id INNER JOIN movie ON movie.movie_id = schedule.movie_id INNER JOIN cinema ON cinema.cinema_id = schedule.cinema_id INNER JOIN user ON orders.user_id = user.user_id WHERE movie.name LIKE ? ORDER BY order_id LIMIT ?,?;";

    const result2 = await query(sql2, ["%" + input + "%", start, pageSize]);
    if (result2.length == 0) {
      data = { error_code: 1, message: "未找到订单内容" };
    } else {
      data = { success_code: 200, data: result, total: total };
    }
  } catch (error) {
    data = { error_code: 1, message: "未找到订单内容" };
  }
  res.json(data);
};

//删除订单
exports.deleteOrder = async (req, res) => {
  try {
    let { orderId, scheduleId, orderSeatInfo } = req.body;
    if (orderId) {
      let sql = "SELECT seat_info FROM schedule WHERE schedule_id = ?";
      const result = await query(sql, [scheduleId]);

        result2 = result[0].seat_info;
        result3 = JSON.parse(result2);
        orderSeatInfo = JSON.parse(orderSeatInfo);
        let tempArr = [];
        result3.forEach((value) => {
          if (orderSeatInfo.indexOf(value) === -1) {
            tempArr.push(value);
          }
        });
        result4 = JSON.stringify(tempArr);
        console.log(result4);

        sql2 = "UPDATE schedule SET seat_info = ? WHERE schedule_id = ?;";
        const result5 = await query(sql2, [result4, scheduleId]);
        sql3 = "DELETE FROM orders WHERE order_id =?";
        const result6 = await query(sql3, [orderId]);
        if (result6) {
          data = { success_code: 200, message: "删除订单成功" };
        }
      }
    }
  catch (error) {
    data = { error_code: 1, message: "删除订单失败" };
  }
  res.json(data);
};

//获取当前页影厅
exports.getCurrentPageHall = async (req, res) => {
  try {
    let { currentPage, pageSize, input } = req.query;
    let start = Number((currentPage - 1) * pageSize);
    pageSize = Number(pageSize);

    let sql =
      "SELECT * FROM hall INNER JOIN cinema ON cinema.cinema_id = hall.cinema_id WHERE cinema.cinema_name LIKE ? ORDER BY hall_id;";
    let total;
    const result = await query(sql, ["%" + input + "%"]);
    if (result.length == 0) {
      data = { error_code: 1, message: "error" };
    } else {
      total = result.length;
    }
    let sql2 =
      "SELECT * FROM hall INNER JOIN cinema ON cinema.cinema_id = hall.cinema_id WHERE cinema.cinema_name LIKE ? ORDER BY hall_id LIMIT ?,?;";

    const result2 = await query(sql2, ["%" + input + "%", start, pageSize]);
    if (result2.length == 0) {
      data = { error_code: 1, message: "error" };
    } else {
      data = { success_code: 200, data: result, total: total };
    }
  } catch (error) {
    data = { error_code: 1, message: "未找到影厅内容" };
  }
  res.json(data);
};

//删除影厅
exports.deleteHall = async (req, res) => {
  try {
    let { cinemaId, hallName } = req.body;
    if (cinemaId) {
      let sql ="SELECT schedule_id FROM schedule WHERE cinema_id = ? AND hall_name = ?;";
      const result = await query(sql, [cinemaId, hallName]);

        result2 = JSON.parse(JSON.stringify(result));
        console.log(result);
        if (result2.length) {
          result2.forEach(async (value) => {
            sql3 = "DELETE FROM schedule WHERE schedule_id = ?;";
            const result3 = await query(sql3, [value.schedule_id]);
          });
        }
      }
    
    sql4 = "DELETE FROM hall WHERE cinema_id = ? AND name = ?";
    const result4 = await query(sql4, [cinemaId, hallName]);
    if (result4.length === 0) {
      data = { error_code: 1, message: "未找到" };
    } else {
      data = { success_code: 200, message: "删除影厅成功" };
    }
  }catch (error) {
    data = { error_code: 1, message: "删除影厅失败" };
  }
  res.json(data);
};

//更新影厅信息
exports.updateHallInfo = async (req, res) => {
  try {
    let { hallId, cinemaId, hallOldName, hallNewName } = req.body;
    if (cinemaId) {
      let sql =
        "SELECT * FROM hall WHERE name = ? AND cinema_id = ? AND hall_id <> ? LIMIT 1;";
      const result = await query(sql, [hallNewName, cinemaId, hallId]);

      if (result[0]) {
        data = { error_code: 1, message: "该影院的影厅已存在！" };
      } else {
        sql =
          "UPDATE schedule SET hall_name = ? WHERE cinema_id = ? AND hall_name = ?";
        const result = await query(sql, [hallNewName, cinemaId, hallOldName]);
        if (result.length == 0) {
          data = { error_code: 1, message: "error" };
        } else {
          let sql =
            "UPDATE hall SET name = ? WHERE cinema_id = ? AND name = ?;";
          const result = await query(sql, [hallNewName, cinemaId, hallOldName]);
          data = { success_code: 200 };
        }
      }
    }
  } catch (error) {
    data = { error_code: 1, message: "更新影影厅信息失败" };
  }
  res.json(data);
};

//获取所有影院
exports.getAllCinema = async (req, res) => {
  let sql = "SELECT cinema_id,cinema_name FROM cinema;";
  const result = await query(sql);
  res.json({ success_code: 200, data: result });
};

//添加影厅信息
exports.addHallInfo = async (req, res) => {
  try {
    let { cinemaId, hallName } = req.body;
    let sql = "SELECT * FROM hall WHERE name = ? AND cinema_id = ? LIMIT 1;";
    const result = await query(sql, [hallName, cinemaId]);
    if (result.length !== 0) {
      data = { error_code: 1, message: "影院名已存在" };
    } else {
      if (result[0]) {
        data = { error_code: 1, message: "新增该影院的影厅已存在" };
      } else {
        sql = "INSERT INTO hall(cinema_id,name) VALUES(?,?);";
        const result = await query(sql, [cinemaId, hallName]);
        data = { success_code: 200, message: "新增影厅信息成功" };
      }
    }
  } catch (error) {
    data = { error_code: 1, message: "新增影厅信息失败" };
  }
  res.json(data);
};

//获取当前页电影
exports.getCurrentPageMovieSchedule = async (req, res) => {
  try {
    let { currentPage, pageSize, input } = req.query;
    let start = Number((currentPage - 1) * pageSize);
    pageSize = Number(pageSize);

    let sql =
      "SELECT * FROM schedule INNER JOIN movie ON schedule.movie_id = movie.movie_id INNER JOIN cinema ON cinema.cinema_id = schedule.cinema_id WHERE movie.name LIKE ? ORDER BY schedule_id ";
    let total;
    const result = await query(sql, ["%" + input + "%"]);
    if (result.length == 0) {
      data = { error_code: 1, message: "error" };
    } else {
      total = result.length;
    }
    let sql2 =
      "SELECT * FROM schedule INNER JOIN movie ON schedule.movie_id = movie.movie_id INNER JOIN cinema ON cinema.cinema_id = schedule.cinema_id WHERE movie.name LIKE ? ORDER BY schedule_id LIMIT ?,?;";

    const result2 = await query(sql2, ["%" + input + "%", start, pageSize]);
    if (result2.length == 0) {
      data = { error_code: 1, message: "error" };
    } else {
      data = { success_code: 200, data: result, total: total };
    }
  } catch (error) {
    data = { error_code: 1, message: "未找到电影内容" };
  }
  res.json(data);
};

//获取所有电影
exports.getAllMovie = async (req, res) => {
  let sql = "SELECT * FROM movie;";
  const result = await query(sql);
  res.json({ success_code: 200, data: result });
};

//获取影院的影厅
exports.getHallByCinemaId = async (req, res) => {
  let cinemaId = req.query.cinemaId;
  let sql = "SELECT hall_id,name FROM hall WHERE cinema_id = ?;";
  const result = await query(sql, [cinemaId]);
  res.json({ success_code: 200, data: result });
};

//获取排片的某天的时间段安排
exports.getHasScheduleDateTime = async (req, res) => {
  let { cinemaId, hallName, showDate } = req.query;
  let sql = 'SELECT show_time FROM schedule WHERE cinema_id = ? AND hall_name = ? AND show_date = ?;';
  const result = await query(sql, [cinemaId,hallName,showDate]);
  res.json({ success_code: 200, data: result });
};

//添加影院信息
exports.addScheduleInfo = async (req, res) => {
  let { movieId,cinemaId,hallName,showDate,showTime,price } = req.body;
  let sql = 'INSERT INTO schedule(movie_id,cinema_id,hall_name,show_date,show_time,price) VALUES(?,?,?,?,?,?);';
  const result = await query(sql, [movieId,cinemaId,hallName,showDate,showTime,price]);
  res.json({ success_code: 200});
};

//删除影厅电影
exports.deleteMovieSchedule = async (req, res) => {
  let { scheduleId } = req.body;
  let sql = 'DELETE FROM schedule WHERE schedule_id = ?';
  const result = await query(sql, [scheduleId]);
  res.json({ success_code: 200});
};